<?php
/*
 * @Author: an
 * @Date: 2021/12/8
 * @Description: 视频直播
 */


namespace App\Http\Controllers\Api;

use App\Http\Controllers\WebApi\Business\ConfigBusiness;
use App\Models\ImLiveStreamLogs;
use App\Services\Aliyun\Live\AuthKeyService;
use App\Services\Configs\DefaultService;
use App\Services\Tencent\Live\StreamService;
use Illuminate\Http\Request;

class LiveController
{
    /**
     * 获取推流地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-09 15:33
     */
    public function pushUrl(Request $request)
    {
        $appName = 'live';
        $expire_in = 43200;
        $streamName = md5($request->user()->id . '$live%');
        //获取公共配置信息
        $option = ConfigBusiness::thirdPartyFirst('live');
        if ($option && $option->value === DefaultService::TENCENT_LIVE) {
            $channel = 'tencent';
            //使用腾讯直播
            $cloud = new StreamService(DefaultService::TENCENT_LIVE);
            $res = $cloud->getPushUrl($streamName, date('Y-m-d H:i:s', time() + $expire_in));
        } else {
            $channel = 'ali';
            $auth = new AuthKeyService();
            $auth->setExpireTime($expire_in);
            $res = $auth->pushUrl($appName, $streamName);//生成推流链接
        }
        $streamLog = new ImLiveStreamLogs();
        //当前用户是否有未过期的当前标识推流地址
//        $data = $streamLog->where('user_id', $request->user()->id)
//            ->where('channel', $channel)
//            ->where('expired_at', '>', time())->first();
//        if ($data) {
//            $res = $data->url;
//        } else {
        $streamLog->create($request->user()->id, $channel, $appName, $streamName, $res, time() + $expire_in);//保存记录
//        }
        return okBack('success', $res);
    }

    /**
     * 获取播流地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-09 15:57
     */
    public function playUrl(Request $request)
    {
        $appName = 'live';
        $streamName = $request->get('streamName');
        $expire_in = 43200;
        if (empty($streamName)) {
            return errBack();
        }
        //获取公共配置信息
        $option = ConfigBusiness::thirdPartyFirst('live');
        if ($option && $option->value === DefaultService::TENCENT_LIVE) {
            //使用腾讯直播
            $cloud = new StreamService(DefaultService::TENCENT_LIVE);
            $res = $cloud->getPlayUrl($streamName, utc_time(date('Y-m-d H:i:s', time() + $expire_in)));
        } else {
            $auth = new AuthKeyService();
            $res = $auth->playUrl($appName, $streamName);
        }
        return okBack($res);
    }
}
